package com.fullertontech.framework.jdbc;

import java.util.Map;
import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;

import io.github.xdiamond.client.XDiamondConfig;

public class PropertiesSourceAdapter implements ApplicationContextAware,EnvironmentAware{
	
	private ApplicationContext applicationContext;
	
	private Environment environment;
	
	private Properties properties;
	
	/**
	 * 获取属性
	 * @return
	 */
	@SuppressWarnings("unchecked")
  public Properties getProperties() {
		try {
			properties=applicationContext.getBean(XDiamondConfig.class).getProperties();
			if(environment instanceof StandardEnvironment) {
				PropertySource<Map<String,Object>> propertySource=(PropertySource<Map<String, Object>>) ((StandardEnvironment)environment).getPropertySources().get("defaultProperties");
				if(propertySource!=null) {
					Map<String, Object> defaultPropertiesMap=propertySource.getSource();
					defaultPropertiesMap.entrySet().forEach(entry->{
						properties.put(entry.getKey(), entry.getValue());
					});
				}
			}
			return properties;
		} catch (Exception e) {
			properties=new Properties();
			if(environment instanceof StandardEnvironment) {
				PropertySource<Map<String,Object>> propertySource=(PropertySource<Map<String, Object>>) ((StandardEnvironment)environment).getPropertySources().get("defaultProperties");
				if(propertySource!=null) {
					Map<String, Object> defaultPropertiesMap=propertySource.getSource();
					defaultPropertiesMap.entrySet().forEach(entry->{
						properties.put(entry.getKey(), entry.getValue());
					});
				}
			}
			return properties;
		}
	}
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext=applicationContext;
	}
	@Override
	public void setEnvironment(Environment environment) {
		this.environment=environment;
	}
}
